#include "Resignature.h"
#include "ui_Resignature.h"
#include "Server.h"
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QBitmap>
#include <QStyleOption>
#include <QMouseEvent>
#include <QPainter>
#include "mymessagebox.h"

Resignature::Resignature(Server *server, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Resignature)
    , serverWindow(server)
    , model(new QStringListModel(this))  // 初始化模型
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    ui->list->setModel(model);  // 将模型设置给QListView
    updateResignationList();  // 初始化时加载申请列表
    connect(ui->list, &QListView::clicked, this, &Resignature::on_list_clicked);
}

Resignature::~Resignature()
{
    delete ui;
}

// 实现窗口拖动功能
void Resignature::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Resignature::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Resignature::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Resignature::on_returnButton_clicked()
{
    this->close();
    serverWindow->show();
}

// 更新补签申请列表
void Resignature::updateResignationList()
{
    QStringList listItems;  // 使用QStringList

    QSqlQuery query;
    query.prepare("SELECT 工号, 姓名, 申请时间 FROM ReSignTable WHERE 申请状态 = 0");
    if (query.exec()) {
        while (query.next()) {
            QString employeeId = query.value(0).toString();
            QString employeeName = query.value(1).toString();
            QString applyTime = query.value(2).toString();

            // 拼接显示信息
            QString listItem = QString("%1 - %2 - %3").arg(employeeId).arg(employeeName).arg(applyTime);
            listItems.append(listItem);  // 添加到列表中
        }
        model->setStringList(listItems);  // 更新模型
    } else {
        qDebug() << "Failed to query ReSignTable:" << query.lastError();
    }
}

// 列表项点击事件
void Resignature::on_list_clicked(const QModelIndex &index)
{
    QStringList data = model->data(index).toString().split(" - ");
    selectedEmployeeId = data.at(0);
    selectedEmployeeName = data.at(1);
    selectedApplyTime = data.at(2);

    // 查询补签详情
    QSqlQuery query;
    query.prepare("SELECT 未打卡日期, 补签原因, 考勤组号 FROM ReSignTable WHERE 工号 = :employeeId AND 姓名 = :employeeName AND 申请时间 = :applyTime");
    query.bindValue(":employeeId", selectedEmployeeId);
    query.bindValue(":employeeName", selectedEmployeeName);
    query.bindValue(":applyTime", selectedApplyTime);

    if (query.exec() && query.next()) {
        ui->date->setText(query.value(0).toString());  // 未打卡日期
        ui->reason->setText(query.value(1).toString());  // 补签原因
        ui->num->setText(query.value(2).toString());  // 考勤组号
    } else {
        qDebug() << "Failed to query ReSignTable details:" << query.lastError();
    }
}

// 清空详情
void Resignature::clearDetails()
{
    ui->num->clear();
    ui->date->clear();
    ui->reason->clear();
    selectedEmployeeId.clear();
    selectedEmployeeName.clear();
}

// 点击"审核通过"按钮
void Resignature::on_yes_clicked()
{
    if (selectedEmployeeId.isEmpty()) {
        // QMessageBox::warning(this, "警告", "请选择申请记录");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("请选择申请记录");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    QSqlQuery query;

    // 修改申请状态为 1（通过）
    query.prepare("UPDATE ReSignTable SET 申请状态 = 1 WHERE 工号 = :employeeId AND 姓名 = :employeeName AND 申请时间 = :applyTime");
    query.bindValue(":employeeId", selectedEmployeeId);
    query.bindValue(":employeeName", selectedEmployeeName);
    query.bindValue(":applyTime", selectedApplyTime);

    if (!query.exec()) {
        qDebug() << "Failed to update ReSignTable:" << query.lastError();
        return;
    }

    // 删除(工号_姓名_1)表中的记录
    QString tableName = QString("`%1_%2_1`").arg(selectedEmployeeId).arg(selectedEmployeeName);
    query.prepare(QString("DELETE FROM %1 WHERE 考勤组号 = :num AND 旷工日期 = :date").arg(tableName));
    query.bindValue(":num", ui->num->text());
    query.bindValue(":date", ui->date->text());

    if (!query.exec()) {
        qDebug() << "Failed to delete from employee table:" << query.lastError();
    }

    // 修改考勤组表中的考勤状态
    QString dateStr = ui->date->text(); // 假设原始值为 "2024-09-20"
    dateStr.replace("-", ""); // 替换 "-" 为 ""
    QString groupTable = QString("`%1_%2`").arg(ui->num->text()).arg(dateStr);
    query.prepare(QString("UPDATE %1 SET 考勤状态 = 2 WHERE 工号 = :employeeId AND 姓名 = :employeeName").arg(groupTable));
    query.bindValue(":employeeId", selectedEmployeeId);
    query.bindValue(":employeeName", selectedEmployeeName);

    if (!query.exec()) {
        qDebug() << "Failed to update attendance status:" << query.lastError();
    }

    // 更新EmployeeAttendanceSummary表
    query.prepare("UPDATE EmployeeAttendanceSummary SET 未打卡数 = 未打卡数 - 1, 补签次数 = 补签次数 + 1 WHERE 工号 = :employeeId AND 姓名 = :employeeName");
    query.bindValue(":employeeId", selectedEmployeeId);
    query.bindValue(":employeeName", selectedEmployeeName);

    if (!query.exec()) {
        qDebug() << "Failed to update EmployeeAttendanceSummary:" << query.lastError();
    }

    // QMessageBox::information(this, "成功", "审核通过");
    MyMessageBox msgBox;
    msgBox.setWindowTitle("成功");
    msgBox.setText("审核通过");
    msgBox.setButton("确定");
    msgBox.exec();

    clearDetails();
    updateResignationList();  // 更新列表
}

// 点击"审核未通过"按钮
void Resignature::on_no_clicked()
{
    if (selectedEmployeeId.isEmpty()) {
        // QMessageBox::warning(this, "警告", "请选择申请记录");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("请选择申请记录");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    QSqlQuery query;

    // 修改申请状态为 2（未通过）
    query.prepare("UPDATE ReSignTable SET 申请状态 = 2 WHERE 工号 = :employeeId AND 姓名 = :employeeName AND 申请时间 = :applyTime");
    query.bindValue(":employeeId", selectedEmployeeId);
    query.bindValue(":employeeName", selectedEmployeeName);
    query.bindValue(":applyTime", selectedApplyTime);

    if (!query.exec()) {
        qDebug() << "Failed to update ReSignTable:" << query.lastError();
        return;
    }

    // QMessageBox::information(this, "成功", "审核未通过");
    MyMessageBox msgBox;
    msgBox.setWindowTitle("成功");
    msgBox.setText("审核未通过");
    msgBox.setButton("确定");
    msgBox.exec();

    clearDetails();
    updateResignationList();  // 更新列表
}
